package com.help10000.rms.mvp.presenter

import android.location.Location
import android.os.Looper
import com.amir.common.api.CustomObserver
import com.amir.common.beans.GeoCoderEntity
import com.amir.common.beans.TencentMapSearchEntity
import com.amir.common.mvp.model.Model
import com.amir.common.mvp.presenter.BasePresenter
import com.amir.common.utils.Constant
import com.amir.common.utils.ToastUtil
import com.amir.common.utils.Utils
import com.help10000.rms.mvp.view.NavigationView
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory
import com.tencent.tencentmap.mapsdk.maps.LocationSource
import com.tencent.tencentmap.mapsdk.maps.TencentMap
import com.tencent.tencentmap.mapsdk.maps.model.CameraPosition
import com.tencent.tencentmap.mapsdk.maps.model.LatLng
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions

class NavigationPresenter(view: NavigationView) : BasePresenter<NavigationView?>(view),
    LocationSource,
    TencentLocationListener {
    var locationChangedListener: LocationSource.OnLocationChangedListener? = null
    var locationManager: TencentLocationManager? = null
    var locationRequest: TencentLocationRequest? = null
    var mTencentMap: TencentMap? = null
    var tencentLocation: TencentLocation? = null
    var currCity: String? = "";
    var firstLocation = true
    fun showLocation() {
        mTencentMap?.setLocationSource(this)
        mTencentMap?.isMyLocationEnabled = true
        //开启定位
        initLocation()
        //开启定位
        val err: Int = locationManager?.requestLocationUpdates(
            locationRequest, this, Looper.myLooper()
        )!!
        when (err) {
            1 -> ToastUtil.show("设备缺少使用腾讯定位服务需要的基本条件")
            2 -> ToastUtil.show(
                "manifest 中配置的 key 不正确"
            )
            3 -> ToastUtil.show("自动加载libtencentloc.so失败")
            else -> {
            }
        }
    }

    fun showMarker(latLng: LatLng) {
        val latLngs = mutableListOf<LatLng>()
        latLngs.add(latLng)
        mTencentMap?.clearAllOverlays()
        var maker = mTencentMap?.addMarker(
            MarkerOptions(latLng)
                .anchor(0.5f, 1f)
        )
        val cameraSigma = CameraUpdateFactory.newCameraPosition(
            CameraPosition(
                latLng, //中心点坐标，地图目标经纬度 //目标缩放级别
                12f,
                0f,
                0f

            )
        ) //目标旋转角 0~360° (正北方为0)

        mTencentMap?.moveCamera(cameraSigma) //移动地图
    }

    fun searchKey(keyword: String, type: Int = 1) {
        val url = "https://apis.map.qq.com/ws/place/v1/suggestion"
        val mapkeyWordSearch = Model.getServer()
            .mapkeyWordSearch(url, keyword, currCity!!, "0", Constant.TencentMapSDK_KEY)
        Model.getObservable(
            mapkeyWordSearch,
            object : CustomObserver<TencentMapSearchEntity>(mvpView) {
                override fun success(t: TencentMapSearchEntity) {
                    mvpView?.searchSuccess(t.data, type)
                }
            })
    }

    /**
     * 地址转坐标
     */
    fun geocoderFromAddress(keyword: String) {
        val url = "https://apis.map.qq.com/ws/geocoder/v1/"
        val mapkeyWordSearch = Model.getServer()
            .Geocoder(url, keyword, Constant.TencentMapSDK_KEY)
        Model.getObservable(
            mapkeyWordSearch,
            object : CustomObserver<GeoCoderEntity>(mvpView) {
                override fun success(t: GeoCoderEntity) {
                    mvpView?.geocoderSuccess(t.result)
                }
            })
    }

    /**
     * 坐标转地址
     */
    fun geocoderFromLocation(location: String?) {
        val url = "https://apis.map.qq.com/ws/geocoder/v1/"
        val mapkeyWordSearch =
            Model.getServer().GeocoderToAddress(url, location, Constant.TencentMapSDK_KEY)
        Model.getObservable(
            mapkeyWordSearch,
            object : CustomObserver<GeoCoderEntity>(mvpView) {
                override fun success(t: GeoCoderEntity) {
                    mvpView?.geocoderSuccess(t.result)
                }
            })
    }

    override fun activate(onLocationChangedListener: LocationSource.OnLocationChangedListener?) {
        //这里我们将地图返回的位置监听保存为当前 Activity 的成员变量
        //这里我们将地图返回的位置监听保存为当前 Activity 的成员变量
        locationChangedListener = onLocationChangedListener
    }

    override fun deactivate() {
        //当不需要展示定位点时，需要停止定位并释放相关资源
        locationManager?.removeUpdates(this)
        locationManager = null
        locationRequest = null
        locationChangedListener = null
    }

    override fun onLocationChanged(tencentLocation: TencentLocation?, i: Int, s: String?) {

        //其中 locationChangeListener 为 LocationSource.active 返回给用户的位置监听器
        //用户通过这个监听器就可以设置地图的定位点位置
        //其中 locationChangeListener 为 LocationSource.active 返回给用户的位置监听器
        //用户通过这个监听器就可以设置地图的定位点位置
        if (i == TencentLocation.ERROR_OK && locationChangedListener != null) {
            this.tencentLocation = tencentLocation
            val location = Location(tencentLocation?.provider)
            //设置经纬度
            location.latitude = tencentLocation?.latitude!!
            location.longitude = tencentLocation.longitude
            //设置精度，这个值会被设置为定位点上表示精度的圆形半径
            location.accuracy = tencentLocation.accuracy
            //设置定位标的旋转角度，注意 tencentLocation.getBearing() 只有在 gps 时才有可能获取
            location.bearing = tencentLocation.bearing
            currCity = tencentLocation.city
//            et_address.setText(tencentLocation.address)

            if (firstLocation) {
                //将位置信息返回给地图
                locationChangedListener!!.onLocationChanged(location)
                firstLocation = false
                val cameraSigma = CameraUpdateFactory.newCameraPosition(
                    CameraPosition(
                        LatLng(
                            tencentLocation.latitude,
                            tencentLocation.longitude
                        ), //中心点坐标，地图目标经纬度 //目标缩放级别
                        12f,
                        0f,
                        0f
                    )
                ) //目标旋转角 0~360° (正北方为0)
                mTencentMap?.moveCamera(cameraSigma) //移动地图
            }

        }


    }

    /**
     * 定位的一些初始化设置
     */
    private fun initLocation() {
        //用于访问腾讯定位服务的类, 周期性向客户端提供位置更新
        locationManager = TencentLocationManager.getInstance(Utils.getContext())
        //创建定位请求
        locationRequest = TencentLocationRequest.create()
        locationRequest?.requestLevel = TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA;
//        locationManager?.requestSingleFreshLocation(null, this, Looper.getMainLooper());

        //设置定位周期（位置监听器回调周期）为3s
//        locationRequest?.interval = 3000
    }

    override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {

    }


}